<template>
  <!-- 整车销量分析 -->
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="4"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <div id="Chartdiv" style="paddingBottom:10px;background:#F2F4F8;">
      <div class="chartSearch">
        <div class="topbtmone">
        整车销量走势情况
        </div>
        <div>
          <el-radio-group v-model="radio" @change="changeDate">
            <el-radio-button v-for="(item, index) in radioList" :key="index" :label="item.value" plain>{{item.text}}</el-radio-button>
          </el-radio-group>
          <el-date-picker
            v-model="searchDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width:220px;">
            <!-- :picker-options="pickerOptions" -->
          </el-date-picker>
        </div>
      </div>
      <div class="Chartmain" style="display:flex;justify-content: space-between;">
        <div class="Chartf">
          <Chart1 :option="option1" :containerStyle="{height: '300px'}"/>
        </div>
      </div>
    </div>
    <div>
      <div class="maintop">
        <el-tabs class="lazyLoadTab" v-model="activeName" @tab-click="handleClick">
          <el-tab-pane class="lazyLoadTabPane" label="团队" name="first"></el-tab-pane>
          <el-tab-pane class="lazyLoadTabPane" label="产品" name="second"></el-tab-pane>
        </el-tabs>
      </div>

      <div class="tabShow">
        <!-- <potenCusModal v-if="activeName === 'first'" :dataSource="dataSource"/> -->
        <FilterTable
          ref="table"
          :columns="columns"
          height="auto"
          v-loading="loading"
          :mergeCellMethod="objectSpanMethod"
          :dataSource="dataSource"
          :isPagination="false"
          :isSelectColumn="false"
          :isColumnFilter="false"
          selectionType="single"
          :onColumnsChange="columns => this.columns = columns"
        ></FilterTable>
      </div>
    </div>


  </div>
</template>

<script>
import {
  qrySalesVinCharts,
  qrySalesVinReports
 } from '@/api/report/retail/SalesVolumeAnalysis';
import {
  getBrandList,
  getSeriesList,
  getModelList,
  getOrgTeam,
  getUserByOrgId
 } from '@/api/report/retail/clueFunnelAnalysis';
import { dictionary } from '@/utils/dictMixin';
import Chart1 from '@/charts/preSale/chart1';
import { authority } from '@/utils/authMixin';
import { arrayObjDeWeight, integration, GetPercent, computedAll, getTextByJs } from '@/utils/index';
import { ObjectAssign, sortRule } from '@/components/DataMerge';
import moment from 'moment';
export default {
  name: 'SalesVolumeAnalysis',
  mixins: [dictionary,authority],
  components: {
    Chart1
  },
  data() {
    return {
      columns: this.createTableColumns(),
      dataSource: [],
      teamdDataSource: [],//团队表格数据
      prodDataSource: [],//产品表格数据
      loading:false,
      initDataSource: [],
      topFilterList: this.createTopFilters(),
      fetchParams: {orderStatus:14041010},
      visible: false,
      dialogTitle: '',
      handleType: '',
      searchDate: '',
      conf:{ add: '新增', edit: '编辑', show: '显示' },
      option1: this.createOption1(),
      radio:'day',
      radioList: [{ value:'day', text:'日' }, { value:'week', text:'周' }, { value:'month', text:'月' }, { value:'quarter', text:'季' }, { value:'year', text:'年' }],
      activeName: 'first',
    };
  },
  watch: {
    searchDate(val){
      console.log(val);
      if (val && val.length > 0) {
        this.radio = 'period';
        this.fetchParams.chartsDimension = 'period';
        this.fetchParams.periodStart = val[0];
        this.fetchParams.periodEnd = val[1];
        this.fetchParams.completeDate = val[1];
        this.qrySalesVinCharts()
      }
    }
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'DATE',
          label: '日期',
          fieldName: 'completeDate',
          placeholder: '',
          dateType: 'exactdate',
          initialValue: moment().format("YYYY-MM-DD")
          // change: (val, fieldName) => {
          //   // console.log(val,fieldName)
          //   this.quarterTime = val;
          // }
        },
        {
          type: 'SELECT',
          label: '销售小组',
          fieldName: 'orgId',
          placeholder: '请选择...',
          itemList: [],
          change: val => {
            // console.log(val,fieldName)
            this.getUserByOrgId(val);
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '销售顾问',
          fieldName: 'consultants',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brandId',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.changeBrandSelect(val);
          }
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'seriesId',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.changeSeriesSelect(val);
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '车型',
          fieldName: 'modelId',
          placeholder: '请选择',
          itemList: [],
          // change: val => {
          //   this.changeModelSelect(val);
          // }
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'orderStatus',
          initialValue: 14041010,
          itemList: [{ value: 14041010, text: '已成交' },{ value: 20651004, text: '已实销上报' }],
        },
      ];
    },
    createOption1(){
      return {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.75)',
          axisPointer: {
            lineStyle: {
              color: 'rgba(0,4,10,0.25)'
            }
          }
        },
        legend: {
          left: '32',
          top: '27',
          icon: 'circle',
          itemWidth: 8,
          itemHeight: 8,
          data: [],
          textStyle: {
            color: 'rgba(0,4,10,0.45)'
          }
        },
        xAxis: {
          type: 'category',
          data: [],
          interval: 0,
          rotate: 45,
          boundaryGap: false,
          axisLabel: {
            textStyle: {
              color: 'rgba(87,90,94,1)'
            }
          },
          axisLine: {
            lineStyle: {
              color: '#EBEBEC'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            textStyle: {
              color: 'rgba(0,4,10,0.25)'
            }
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(0,4,10,0.08)'
            }
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: 'rgba(0,4,10,0.08)'
            }
          }
        },
        series: [],
        color:['#1890FF', '#FF4D4F', '#FFC53D'],
      };
    },

    async qrySalesVinCharts() {
      let fetchParams = {...this.fetchParams}
        switch (this.radio) {
          case 'week':
            var weekOfday = moment(fetchParams.completeDate, 'YYYY-MM-DD').format('E'); //计算指定日期是这周第几天
            var last_monday = moment(fetchParams.completeDate).subtract(weekOfday-1, 'days').format('YYYY-MM-DD');//周一日期
            var last_sunday = moment(fetchParams.completeDate).add(7-weekOfday, 'days').format('YYYY-MM-DD');//周日日期
            console.log(weekOfday)
            var week = moment(last_sunday).week()
            if (week<10) {
              week = '0'+week
            }
            fetchParams.completeDate = last_sunday.split('-')[0] + '-' + week;
            break;
        }
      const res = await qrySalesVinCharts(fetchParams);
      // console.log('销售顾问', res)
      if (res.resultCode === 200) {
        let arr = [],option1 = this.createOption1();
        option1.legend.data = res.data.legend;
        switch (this.radio) {
          case 'month':
            res.data.xAxis.map(x=>{
              option1.xAxis.data.push(x+"月")
            })
            break;
          case 'quarter':
            res.data.xAxis.map(x=>{
              option1.xAxis.data.push(`第${x}季度`)
            })
            break;
          default:
            option1.xAxis.data = res.data.xAxis;
            break;
        }
        switch (this.radio) {
          case 'period':
            option1.xAxis.data = res.data.xAxis;
            res.data.chartsSeriesList.map(x=>{
              option1.series.push({
                name:'整车销量',
                type: 'line',
                smooth: true,
                data: x.data.split(","),
              })
            })
            break;
          default:
            res.data.chartsSeriesList.map(x=>{
              option1.series.push({
                name:x.name,
                type: 'line',
                smooth: true,
                data: x.data.split(","),
              })
            })
            break;
        }

        this.option1 = option1;
        // // console.log(this.option1)
        // this.initDataSource = res.data.detailVO;
      }
    },

    async qrySalesVinReports() {
      this.loading = true;
      const res = await qrySalesVinReports(this.fetchParams);
      if (res.resultCode === 200) {
        this.loading = false;
        let list = res.data.salesVinTeamTableList;//团队
        if (list.length > 0) {
          list = sortRule(list, 'orgId');
          let all = computedAll([...this.columns],list)
          all['orgId'] = 'all';
          all['consultant'] = 'all';
          all['orgName'] = '全部';
          all['consultantName'] = '全部';
          list.unshift(all);
          list.forEach(x=>{
              x['monthSame'] = GetPercent(x.monthSum - x.monthYoy,x.monthYoy)
              x['monthSequential'] = GetPercent(x.monthSum - x.monthMom,x.monthMom)
              x['quarterSame'] = GetPercent(x.quarterSum - x.quarterYoy,x.quarterYoy)
              x['quarterSequential'] = GetPercent(x.quarterSum - x.quarterQoq,x.quarterQoq)
              x['yearSame'] = GetPercent(x.yearSum - x.yearYoy,x.yearYoy)
          })
        }
        console.log(list)
        this.teamdDataSource = list;
        this.dataSource = list;
        // table数据处理
        let columns2 = this.createTableColumns2()
        let list2 = res.data.salesVinProductTableList;//产品
        if (list2.length > 0) {
          list2 = sortRule(list2, 'seriesId');
          let all = computedAll([...columns2],list2)
          all['seriesId'] = 'all';
          all['modelId'] = 'all';
          all['seriesName'] = '全部';
          all['modelName'] = '全部';
          list2.unshift(all);
          list2.forEach(x=>{
              x['monthSame'] = GetPercent(x.monthSum - x.monthYoy,x.monthYoy)
              x['monthSequential'] = GetPercent(x.monthSum - x.monthMom,x.monthMom)
              x['quarterSame'] = GetPercent(x.quarterSum - x.quarterYoy,x.quarterYoy)
              x['quarterSequential'] = GetPercent(x.quarterSum - x.quarterQoq,x.quarterQoq)
              x['yearSame'] = GetPercent(x.yearSum - x.yearYoy,x.yearYoy)
          })
        }
        this.prodDataSource = list2;
      }
    },
    async getOrgTeam() {
      const res = await getOrgTeam();
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'orgId').itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    async getUserByOrgId(val) {
      const res = await getUserByOrgId({ orgId: val });
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'consultants').itemList = res.data.map(x => ({ value: x.userId, text: x.userName }));
        this.topFilterList.find(item => item.fieldName === 'consultants').initialValue = '';
      }
    },
    changeHandle(val) {
      // console.log(val)
      this.radio = 'day'
      if (val.completeDate) {
        val.periodStart = val.completeDate;
        val.periodEnd = val.completeDate;
      }else{
        val.completeDate = moment().format("YYYY-MM-DD");
        val.periodStart = moment().format("YYYY-MM-DD");
        val.periodEnd = moment().format("YYYY-MM-DD");
      }
      if (!val.chartsDimension) {
        val.chartsDimension = this.radio;
      }
      if (val.consultants && val.consultants.length > 0) {
        val.consultant = getTextByJs(val.consultants);
      }
      if (val.modelId && val.modelId.length === 0 && val.brandId && val.seriesId) {
        let list = this.topFilterList.find(item=>item.fieldName==='modelId').itemList;
        val.modelIds = getTextByJs(list,'value')
      }else if (val.modelId && val.modelId.length > 0) {
        val.modelIds = getTextByJs(val.modelId)
      }else{
        val.modelIds = val.modelId
      }
      //解决参数问题接口modelId
      let fetchParams = {...val}
      fetchParams.modelId = fetchParams.modelIds

      this.fetchParams = Object.assign({}, val);
      this.radio = 'day';
      this.qrySalesVinCharts()
      this.qrySalesVinReports()
    },
    handleClick(tab, event) {
      console.log(this.activeName);
      if (this.activeName === 'first') {
        this.columns = this.createTableColumns()
        this.dataSource = this.teamdDataSource
      } else {
        this.columns = this.createTableColumns2()
        this.dataSource = this.prodDataSource
      }
    },
    collapseHandle() {
      // this.$nextTick(() => {
      //   this.BaseTable.EXECUTE_RESET_HEIGHT();
      // });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    changeDate(value){
      // console.log(this.rowDate)
      let val = {...this.fetchParams}
      if (!val.completeDate) {
        val.completeDate = moment().format("YYYY-MM-DD");
      }
      if (value) {
        val.chartsDimension = value
      }
      this.fetchParams = Object.assign({}, val);
      this.qrySalesVinCharts()
    },
    createTableColumns() {
      return [
        {
          title: '销售小组',
          dataIndex: 'orgName'
        },
        {
          title: '销售顾问',
          dataIndex: 'consultantName'
        },
        {
          title: '日销量',
          dataIndex: 'daySum'
        },
        {
          title: '周销量',
          dataIndex: 'weekSum'
        },
        {
          title: '月度',
          align: 'center',
          children: [
            {
              title: '月累计',
              dataIndex: 'monthSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'monthYoy',
            },
            {
              title: '月同比',
              dataIndex: 'monthSame',
              render: props => {
                return <span style={props.row.monthSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSame}</span>;
              }
            },
            {
              title: '上月同期累计',
              dataIndex: 'monthMom',
            },
            {
              title: '月环比',
              dataIndex: 'monthSequential',
              render: props => {
                return <span style={props.row.monthSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSequential}</span>;
              }
            },
          ]
        },
        {
          title: '季度',
          align: 'center',
          children: [
            {
              title: '季累计',
              dataIndex: 'quarterSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'quarterYoy',
            },
            {
              title: '季同比',
              dataIndex: 'quarterSame',
              render: props => {
                return <span style={props.row.quarterSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSame}</span>;
              }
            },
            {
              title: '上季同期累计',
              dataIndex: 'quarterQoq',
            },
            {
              title: '季环比',
              dataIndex: 'quarterSequential',
              render: props => {
                return <span style={props.row.quarterSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSequential}</span>;
              }
            },
          ]
        },
        {
          title: '年度',
          align: 'center',
          children: [
            {
              title: '年累计',
              dataIndex: 'yearSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'yearYoy',
            },
            {
              title: '年同比',
              dataIndex: 'yearSame',
              render: props => {
                return <span style={props.row.yearSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.yearSame}</span>;
              }
            },
          ]
        },
      ];
    },
    createTableColumns2() {
      return [
        {
          title: '车系',
          dataIndex: 'seriesName'
        },
        {
          title: '车型',
          dataIndex: 'modelName'
        },
        {
          title: '日销量',
          dataIndex: 'daySum'
        },
        {
          title: '周销量',
          dataIndex: 'weekSum'
        },
        {
          title: '月度',
          align: 'center',
          children: [
            {
              title: '月累计',
              dataIndex: 'monthSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'monthYoy',
            },
            {
              title: '月同比',
              dataIndex: 'monthSame',
              render: props => {
                return <span style={props.row.monthSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSame}</span>;
              }
            },
            {
              title: '上月同期累计',
              dataIndex: 'monthMom',
            },
            {
              title: '月环比',
              dataIndex: 'monthSequential',
              render: props => {
                return <span style={props.row.monthSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSequential}</span>;
              }
            },
          ]
        },
        {
          title: '季度',
          align: 'center',
          children: [
            {
              title: '季累计',
              dataIndex: 'quarterSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'quarterYoy',
            },
            {
              title: '季同比',
              dataIndex: 'quarterSame',
              render: props => {
                return <span style={props.row.quarterSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSame}</span>;
              }
            },
            {
              title: '上季同期累计',
              dataIndex: 'quarterQoq',
            },
            {
              title: '季环比',
              dataIndex: 'quarterSequential',
              render: props => {
                return <span style={props.row.quarterSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSequential}</span>;
              }
            },
          ]
        },
        {
          title: '年度',
          align: 'center',
          children: [
            {
              title: '年累计',
              dataIndex: 'yearSum',
            },
            {
              title: '去年同期累计',
              dataIndex: 'yearYoy',
            },
            {
              title: '年同比',
              dataIndex: 'yearSame',
              render: props => {
                return <span style={props.row.yearSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.yearSame}</span>;
              }
            },
          ]
        },
      ];
    },

    // 合并行或列的计算方法
    // row:当前行 column:当前列 rowIndex:当前行号 columnIndex:当前列号
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          row.orgName = '全部';
          return [1, 2];
        } else {
          let key = this.activeName === 'first'?'orgId':'seriesId';
          // 与上一行不相等
          if (row[key] !== (this.dataSource[rowIndex - 1] || {})[key]) {
            // 与上一行不相等,与下一行相等
            if (row[key] === (this.dataSource[rowIndex + 1] || {})[key]) {
              return {
                rowspan: this.dataSource.filter(x => row[key] === x[key]).length || 1,
                colspan: 1
              };
            } else {   // 与上一行不相等,与下一行不相等
              return [1, 1];
            }
          } else {     // 与上一行相等
            return [0, 0];
          }
        }
      } else if (columnIndex === 1) {
        if (rowIndex === 0) {
          return [0, 0];
        }
      }
    },
    async getBrandList() {
      const res = await getBrandList();
      if (res.resultCode === 200) {
        this.topFilterList.find(item=>item.fieldName==='brandId').itemList = res.data.map(x => ({ value: x.brandId, text: x.brandName }));
        // this.topFilterList = [...this.topFilterList]
      }
    },
    async changeBrandSelect(brandsid) {
      if (!brandsid) {
        this.topFilterList.find(item=>item.fieldName==='seriesId').initialValue = '';
        this.topFilterList.find(item=>item.fieldName==='seriesId').itemList = [];
        this.topFilterList.find(item=>item.fieldName==='modelId').initialValue = '';
        this.topFilterList.find(item=>item.fieldName==='modelId').itemList = [];
      } else {
        const res = await getSeriesList(brandsid);
        if (res.resultCode === 200) {
          this.topFilterList.find(item=>item.fieldName==='seriesId').itemList = res.data.map(x => ({ value: x.seriesId, text: x.seriesName }));
        }
      }
    },
    async changeSeriesSelect(seriessid) {
      const brandsid = this.topFilterList.find(item=>item.fieldName==='brandId').initialValue;
      if (!brandsid || !seriessid) {
        this.topFilterList.find(item=>item.fieldName==='modelId').initialValue = '';
        this.topFilterList.find(item=>item.fieldName==='modelId').itemList = [];
      } else {
        const res = await getModelList(brandsid, seriessid);
        if (res.resultCode === 200) {
          this.topFilterList.find(item=>item.fieldName==='modelId').itemList = res.data.map(x => ({ value: x.modelId, text: x.modelName }));
        }
      }
    },
  },
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getBrandList()
    this.getOrgTeam()
    this.changeHandle({orderStatus:14041010})
  }
};
</script>

<style lang="less" scoped>
#Chartdiv{

  .chartSearch{
    display:flex;
    align-items: center;
    justify-content: space-between;
    padding:0 32px;
    line-height: 58px;
    background:#fff;
    border-bottom: 1px solid rgba(0,4,10,0.08);
    .topbtmone{
      font-size: 16px;
      font-weight: 600;
    }
  }
  .Chartmain{
    background:#fff;
    .Chartleft{
      border-left: 1px dashed rgba(0,4,10,0.08);
    }
  }
}
.Chartf{
  width:100%;
  // max-height: 400px;
  .ChartTop{
    font-size: 16px;
    font-weight: 600;
    line-height: 58px;
    padding-left:32px;
  }
}


.maintop{
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  overflow: hidden;
  background:#FFF;
  padding-left: 12px;
  padding-right: 12px;
  border-bottom: 1px solid rgba(0,4,10,0.08);
  .lazyLoadTab {
    /deep/ .el-tabs__header,.is-top{
      margin-bottom: 0;
    }
    /deep/ .el-tabs__active-bar{
      height: 4px;
    }
    /deep/ .el-tabs__nav-wrap::after{
      height: 0;
    }
  }
}

.tabShow{
  min-height: 300px;
}
</style>
